<?php

namespace app\controller\common;

use app\controller\ApiBaseController;
use AlibabaCloud\Tea\Exception\TeaError;
use app\ConstVar;
use app\model\SmsCodeModel;

/**
 * sms公共方法
 */
class Sms extends ApiBaseController
{

    /**
     * 调用阿里云，发送短信验证码
     */
    public function getSmsCode()
    {
        $strPhone = param_filter($this->request->param('phone', ''), 'string');
        if (empty($strPhone)) {
            return api_response([], '请输入手机号码', 0);
        }

        // 生成验证码，并保存在数据库
        $strVerifyCode = generateRandomVerifyCode(ConstVar::SMS_VERIFY_CODE_LENTH);
        $boolSave = (new SmsCodeModel())->addSmsCode($strPhone, $strVerifyCode);
        if (!$boolSave) {
            return api_response([], '系统错误，请重试', 0);
        }

        try {
            $boolSend = sendVerifyCode($strPhone, $strVerifyCode);
            if ($boolSend) {
                return api_response([], '发送成功', 1);
            } else {
                return api_response([], '发送失败', 0);
            }
        } catch (TeaError $e) {
            return api_response([], $e->message, 0);
        }
    }
}
